/**
 * Copyright &copy; 2012-2014 ThinkGem All rights reserved.
 */
package com.sx.admin.shiro;

import com.sx.core.CardConstants;
import com.sx.core.model.Operator;
import com.sx.core.mybatis.SessionTemplate;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 系统安全认证实现类
 */
public class SecuritySystemAuthorizingRealm extends AuthorizingRealm {

	private Logger logger = LoggerFactory.getLogger(getClass());


	@Autowired
	SessionTemplate sessionTemplate;
	
	/**
	 * 认证回调函数, 登录时调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
		SecurityUsernamePasswordToken token = (SecurityUsernamePasswordToken) authcToken;

		// 校验用户名密码
		String username = token.getUsername();
		Operator operator=sessionTemplate.get(Operator.class,username);
		if(operator!=null){
			if(operator.getFlag().charAt(0)=='0'){
				throw new DisabledAccountException("用户被禁用");
			}
			if(operator.getStartdate().after(new Date())){
				throw new DisabledAccountException("用户还未被使用");
			}
			if(operator.getExpdate().before(new Date())){
				throw new DisabledAccountException("用户已过期");
			}
			List<String> permis=new ArrayList<>();
			byte[] salt = CardConstants.password_salt.getBytes();
			return new SimpleAuthenticationInfo(new AdminPrincipal(operator,permis),operator.getOperpin(), ByteSource.Util.bytes(salt), getName());
		}
		return null;
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		AdminPrincipal principal = (AdminPrincipal) principals.fromRealm(getName()).iterator().next();
		if (principal!= null) {
//			SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
//			authorizationInfo.addStringPermissions(userRoleFacade.listOperatorFeatures(principal.getOperator()));
//			return authorizationInfo;
			return  principal.getAuthorizationInfo();
		}
		return null;
	}

	/**
	 * 设定密码校验的Hash算法与迭代次数
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("MD5");
		setCredentialsMatcher(matcher);
	}



}
